<?php

namespace App\HttpController\admin;


use App\Common\Admin\Admin;
use App\Common\OA\OA;
use App\H;
use App\HttpController\ControllerBase;
use App\Model\t_t_user;
use EasySwoole\Component\Openssl;
use EasySwoole\VerifyCode\Conf;

class login extends ControllerBase
{
    public function funcLoginErrCountKey()
    {
        return 'login_err_count|' . $this->funcGetWebIP();
    }

    public function funcVCodeKey()
    {
        return Admin::funcVCodeKey__redis($this->funcGetWebIP());
    }

    public function funcGetAppAdmin()
    {
        return new Admin();
    }


    //登陆
    public function index()
    {
        $username = $this->request()->getRequestParam('username');
        $pwd = $this->request()->getRequestParam('password');
        $code = $this->request()->getRequestParam('code');


        $v = new \EasySwoole\Validate\Validate();
        $v->addColumn('username')->required('账号不能为空');
        $v->addColumn('password')->required('密码不能为空');

        if (!$this->validate($v))
        {
            return $this->funcWriteValidate($v);
        }


        if ($this->funcIsCheckVCode())
        {
            $app = $this->funcGetAppAdmin();
            if (!$app->funcCheckVCode($code))
            {
                return $this->funcWriteErr(-90, '验证码错误', ['show_code' => true]);
            }
        }


        $pwd = base64_decode($pwd);

        //手机查找
        $arr_acc = $this->db()
            ->where('user_phone', $username)
            ->getOne(t_t_user::table());
        if ($arr_acc === null)
        {
            //邮件查找
            $arr_acc = $this->db()
                ->where('user_mail', $username)
                ->getOne(t_t_user::table());
            if ($arr_acc === null)
            {
                return $this->funcWriteErr(-100, '用户不存在');
            }
        }

        $entity_user = new t_t_user($arr_acc);


        $openssl = new Openssl(H::funcKey('abc'));
        $pwd_enc = $openssl->encrypt($pwd);

        if ($pwd_enc != $entity_user->user_pwd)
        {
            //密码不正确，3次需要输验证码

            $show_code = true;
            if (!$this->funcIsCheckVCode())
            {
                $show_code = false;

                $this->redis()->incr($this->funcLoginErrCountKey());
                $this->redis()->setTimeout($this->funcLoginErrCountKey(), 5 * 60);
            }

            return $this->funcWriteErr(-200, '密码错误', ['show_code' => $show_code]);
        }


        //登陆成功
        $nonce_str = H::funcGetOrderID();
        $enc_code = OA::funcAdminGetSign($entity_user->user_phone, $entity_user->user_id, $nonce_str);


        $data = [
            'OA__x' => $entity_user->user_phone,
            'OA__acc_id' => $entity_user->user_id,
            'OA__nonce_str' => $nonce_str,
            'OA__ENC_CODE' => $enc_code,
        ];

        //记录session
        foreach ($data as $key => $val)
        {
            $this->xsession()->set($key, $val);
        }

        $this->commonR()->data['token'] = $openssl->encrypt($this->xsession()->sid());


        $this->funcWriteCommonR();
    }


    /**
     * 需要显示验证码
     *
     * @return bool
     * @throws \Exception
     */
    public function funcIsCheckVCode()
    {
        $err_count = $this->redis()->get($this->funcLoginErrCountKey());
        if ($err_count >= 3)
        {
            return true;
        }


        return false;
    }

    public function vcode()
    {
        $config = new Conf();
        $config->setTemp(\h::funcGetConf('SYS.upload'));

        $code = new \EasySwoole\VerifyCode\VerifyCode($config);


        $vcode = rand(1000, 9999);
        $this->redis()->set($this->funcVCodeKey(), $vcode, 60);


        $this->response()->withHeader('Content-Type', 'image/png');
        $this->response()->write($code->DrawCode($vcode)->getImageByte());
    }
}